<?php
class Doctrine_Template_Listener_Authorable extends Doctrine_Record_Listener{
    /**
     * Array of authorable options
     *
     * @var string
     */
    protected $_options = array();

    /**
     * __construct
     *
     * @param string $array
     * @return void
     */
    public function __construct(array $options){
        $this->_options = $options;
    }

    public function preInsert(Doctrine_Event $event){
      if ($this->_options['author']['enabled']){
        $this->setUserForColumn($event, 'author');
      }
      if ($this->_options['modifier']['enabled']){
        $this->setUserForColumn($event, 'modifier');
      }
      if ($this->_options['author_name']['enabled']){
        $this->setAuthorName($event, 'author_name');
      }
      if ($this->_options['modifier_name']['enabled']){
        $this->setAuthorName($event, 'modifier_name');
      }
    }

    public function preUpdate(Doctrine_Event $event){
      if ($this->_options['modifier']['enabled']){
        $this->setUserForColumn($event, 'modifier');
      }
      if ($this->_options['author']['enabled']){
        $record = $event->getInvoker();
        $field = $record->getTable()->getFieldName($this->_options['author']['column']);
        if (is_null($record->$field)) $this->setUserForColumn($event, 'author');
      }
      if ($this->_options['author_name']['enabled']){
        $record = $event->getInvoker();
        $field = $record->getTable()->getFieldName($this->_options['author_name']['column']);
        if (is_null($record->$field)) $this->setAuthorName($event, 'author_name');
      }
      if ($this->_options['modifier_name']['enabled']){
        $record = $event->getInvoker();
        $field = $record->getTable()->getFieldName($this->_options['modifier_name']['column']);
        if (is_null($record->$field)) $this->setAuthorName($event, 'modifier_name');
      }
    }

    
    private function setUserForColumn($event, $column){
      $record = $event->getInvoker();
      $user = sfContext::getInstance()->getUser();
      $method = $this->_options[$column]['method'];
      if (method_exists($user, $method)){
        $id = $user->$method();
        $name = $record->getTable()->getFieldName($this->_options[$column]['column']);
        if ( ! $record->$name) $record->$name = $id;
      }
    }

    private function setAuthorName($event, $column){
      $record = $event->getInvoker();
      $user = sfContext::getInstance()->getUser();
      $method = $this->_options[$column]['method'];
      if (method_exists($user, $method)) $name = $user->$method();
      elseif (isset($this->_options[$column]['default_name'])) $name = $this->_options[$column]['default_name'];
      else $name = 'Anonymous';
      $columnName = $record->getTable()->getFieldName($this->_options[$column]['column']);
      if (!$record->$columnName) $record->$columnName = $name;
    }

}
